#include "redis_util.h"

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <hiredis/hiredis.h>
#include "data_type.h"

extern uint8_t *sn;
/**
 * @brief 根据集合名称，取出Redis中的数据
 * 
 * @param group 
 * @param res
 */
int redis_pull_array(uint8_t *group, uint8_t *res){
    redisContext *conn;
    redisReply *reply;
    
    // 连接Redis服务器（默认127.0.0.1:6379）
    conn = redisConnect("127.0.0.1", 6379);
    if (conn == NULL || conn->err) {
        if (conn) {
            printf("Connection error: %s\n", conn->errstr);
            redisFree(conn);
        } else {
            printf("Connection error: can't allocate redis context\n");
        }
    }
    
    // 获取值
    reply = redisCommand(conn, "HVALS %s", group);
    if (reply->type == REDIS_REPLY_STRING) {
        printf("Got value: %s\n", reply->str);
    }
    if(reply->type == REDIS_REPLY_NIL){
        printf("%s 不存在\n", group);
        freeReplyObject(reply);
        redisFree(conn);
        return -1;
    }
    memmove(res, reply->str, sizeof(reply->str));
    freeReplyObject(reply);

    // 清理连接
    redisFree(conn);
    return 0;
}

/**
 * @brief 取出Redis中的数据
 * 
 * @param key 
 * @param res
 */
int redis_pull_data(uint8_t *group, uint8_t *key, uint8_t *res){
    redisContext *conn;
    redisReply *reply;
    
    // 连接Redis服务器（默认127.0.0.1:6379）
    conn = redisConnect("127.0.0.1", 6379);
    if (conn == NULL || conn->err) {
        if (conn) {
            printf("Connection error: %s\n", conn->errstr);
            redisFree(conn);
        } else {
            printf("Connection error: can't allocate redis context\n");
        }
    }
    
    // 获取值
    reply = redisCommand(conn, "HGET %s %s", group, key);
    if (reply->type == REDIS_REPLY_STRING) {
        printf("Got value: %s\n", reply->str);
    }
    if (reply->type == REDIS_REPLY_NIL) {
        printf("%s %s 不存在\n", group, key);
        freeReplyObject(reply);
        redisFree(conn);
        return -1;
    }
    memmove(res, reply->str, sizeof(reply->str));
    freeReplyObject(reply);

    // 清理连接
    redisFree(conn);
    return 0;
}
/**
 * @brief 向Redis中保存数据
 * 
 * @param key
 * @param val
 */
int redis_push_data(uint8_t *group, uint8_t *key, uint8_t *val){

    redisContext *conn;
    redisReply *reply;

    // 连接Redis服务器（默认127.0.0.1:6379）
    conn = redisConnect("127.0.0.1", 6379);
    if (conn == NULL || conn->err) {
        if (conn) {
            printf("Connection error: %s\n", conn->errstr);
            redisFree(conn);
        } else {
            printf("Connection error: can't allocate redis context\n");
        }
    }

    // 设置键值对
    reply = redisCommand(conn, "HSET %s %s %s", group, key, val);
    freeReplyObject(reply);
    // 清理连接
    redisFree(conn);
    printf("Set key complete\n");
}
